<template>
  <div class="leave-page">
    <!-- 导航栏 -->
    <NavBar title="闲置买卖">
      <template #right>
        <van-icon name="plus" size="20" color="white" @click="goToAdd" />
      </template>
    </NavBar>
    
    <!-- 内容区域 -->
    <div class="page-content">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索闲置商品..."
          @search="handleSearch"
          @clear="handleClear"
        />
      </div>
      
      <!-- 列表 -->
      <div class="leave-list">
        <div 
          v-for="trade in tradeList" 
          :key="trade.tradeId"
          class="leave-item card"
          @click="goToDetail(trade.tradeId)"
        >
          <!-- 商品图片 -->
          <div class="item-image" v-if="leave.images && leave.images.length">
            <img :src="leave.images[0]" alt="商品图片" />
            <div class="image-count" v-if="leave.images.length > 1">
              {{ leave.images.length }}张
            </div>
          </div>
          
          <!-- 商品信息 -->
          <div class="item-content">
            <div class="title">{{ leave.title }}</div>
            <div class="content">{{ leave.content }}</div>
            
            <!-- 价格信息 -->
            <div class="price-info">
              <div class="current-price">¥{{ leave.price }}</div>
              <div class="original-price" v-if="leave.originalPrice">
                原价: ¥{{ leave.originalPrice }}
              </div>
            </div>
            
            <!-- 商品详情 -->
            <div class="item-info">
              <div class="info-item">
                <span class="label">成色:</span>
                <span class="value">{{ leave.condition }}</span>
              </div>
              <div class="info-item">
                <span class="label">地点:</span>
                <span class="value">{{ leave.location }}</span>
              </div>
              <div class="info-item">
                <span class="label">联系:</span>
                <span class="value contact">{{ leave.contactWay }}</span>
              </div>
            </div>
            
            <!-- 底部信息 -->
            <div class="item-footer">
              <div class="user-info">
                <img :src="leave.userAvatar || '/images/default-avatar.png'" alt="头像" class="avatar" />
                <span class="nickname">{{ leave.userNickname }}</span>
                <span class="time">{{ formatTime(leave.createTime) }}</span>
              </div>
              <div class="stats">
                <span class="stat-item">
                  <van-icon name="eye-o" size="14" />
                  {{ leave.viewCount }}
                </span>
                <span class="stat-item">
                  <van-icon name="chat-o" size="14" />
                  {{ leave.commentCount }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore">
        <van-button 
          :loading="loading" 
          @click="loadMore"
          type="default"
          size="small"
        >
          {{ loading ? '加载中...' : '加载更多' }}
        </van-button>
      </div>
      
      <!-- 空状态 -->
      <van-empty 
        v-if="!loading && tradeList.length === 0"
        description="暂无闲置商品"
        image="search"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavBar from '@/components/Common/NavBar.vue'
import { tradeApi } from '@/api/trade'
import type { TradeItem } from '@/api/trade'
import { formatTime } from '@/utils/time'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const tradeList = ref<TradeItem[]>([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(0)  // 从0开始
const pageSize = 10

// 加载列表数据
const loadList = async (isRefresh = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const params = {
      pageNo: isRefresh ? 0 : currentPage.value,  // 从0开始
      pageSize: pageSize,
      str: searchKeyword.value || undefined  // 搜索关键词
    }
    
    const response = await tradeApi.getList(params)
    
    if (response.code === 1 && response.data) {
      const { list, total } = response.data
      
      if (isRefresh) {
        tradeList.value = list || []
        currentPage.value = 0
      } else {
        tradeList.value.push(...(list || []))
      }
      
      hasMore.value = (list || []).length === pageSize
      currentPage.value++
    } else {
      showToast(response.msg || '加载失败')
    }
  } catch (error: any) {
    console.error('加载二手交易列表失败:', error)
    if (error.message?.includes('401') || error.message?.includes('未授权')) {
      showToast('请先登录')
    } else {
      showToast('加载失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 0
  loadList(true)
}

// 清除搜索
const handleClear = () => {
  searchKeyword.value = ''
  currentPage.value = 0
  loadList(true)
}

// 加载更多
const loadMore = () => {
  loadList()
}

// 跳转到发布页面
const goToAdd = () => {
  router.push('/leave/add')
}

// 跳转到详情页面
const goToDetail = (id: string) => {
  router.push(`/leave/${id}`)
}

// 页面加载时获取数据
onMounted(() => {
  loadList(true)
})
</script>

<style scoped>
.leave-page {
  min-height: 100vh;
  background-color: #f1f1f1;
}

.page-content {
  padding: 0 16px 16px;
}

.search-bar {
  background: white;
  border-radius: 8px;
  margin: 16px 0;
  overflow: hidden;
}

.leave-list {
  margin-bottom: 16px;
}

.leave-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  gap: 12px;
}

.leave-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.item-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  flex-shrink: 0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-count {
  position: absolute;
  bottom: 4px;
  right: 4px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-price {
  font-size: 18px;
  font-weight: 600;
  color: #e74c3c;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.item-info {
  font-size: 12px;
  color: #666;
}

.info-item {
  display: inline-block;
  margin-right: 12px;
  margin-bottom: 4px;
}

.label {
  color: #999;
}

.value {
  color: #333;
}

.contact {
  color: #636DEA;
}

.item-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: auto;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 12px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.stats {
  display: flex;
  gap: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 16px 0;
}
</style>